package com.pine.app.module.security.oauth.plugin.impl.loginTGT;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.pine.app.module.security.oauth.config.properties.OAuth2Properties;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoyuan
 * @create 2020/3/19 20:47
 **/
@Slf4j
public class InMemoryOauthTgtService implements OauthTgtService {

    private OAuth2Properties.Tgt tgt;
    private Cache<String,OauthTgtDTO> TGTCache ;

    private Cache<String,String> listCache ;
    private Cache<String,Integer> loginNameCache ;
    public InMemoryOauthTgtService(OAuth2Properties.Tgt tgt){
        this.tgt = tgt;
        TGTCache = CacheBuilder.newBuilder().expireAfterWrite(this.tgt.getExpire(), TimeUnit.MILLISECONDS).build();
        listCache = CacheBuilder.newBuilder().expireAfterWrite(60*1000, TimeUnit.MILLISECONDS).build();
        loginNameCache = CacheBuilder.newBuilder().expireAfterWrite(this.tgt.getExpire(), TimeUnit.MILLISECONDS).build();
    }


    @Override
    public String createTGT() {
        String tgt = UUID.randomUUID().toString();
        listCache.put(tgt,tgt);
        return tgt;
    }

    @Override
    public boolean checkTGT(String id) {
        try{
            Object s =    listCache.getIfPresent(id);
            if(s!=null){
                return true;
            }
        }catch (Exception e){
            log.error("检查票据错误", e);
            return false;
        }
        return false;
    }

    @Override
    public void save(OauthTgtDTO tgtDTO) {
        TGTCache.put(tgtDTO.getId(),tgtDTO);
       Integer integer =  loginNameCache.getIfPresent(tgtDTO.getLoginName());
       if(integer==null){
           integer =1;
       }else{
           integer+=1;
       }
        loginNameCache.put(tgtDTO.getLoginName(),integer);


    }

    @Override
    public void remove(String tgtId) {
        OauthTgtDTO tgtDTO = TGTCache.getIfPresent(tgtId);
        if(tgtDTO!=null){
            loginNameCache.invalidate(tgtDTO.getLoginName());
            listCache.invalidate(tgtId);
            TGTCache.invalidate(tgtId);
        }

    }

    @Override
    public OauthTgtDTO getOauthTgtDTO(String tgtId) {
        return TGTCache.getIfPresent(tgtId);
    }

    @Override
    public int getLoginCount(String loginName) {
        return loginNameCache.getIfPresent(loginName);
    }
}
